//
//  ACCircleView.m
//  MonitoringSystem
//
//  Created by JiaKang.Zhong on 16/4/29.
//  Copyright © 2016年 YTYangK. All rights reserved.
//
/*
      此类对外不提供任何的方法，参数，不让外界去修改内部的元素。
 */
#import "ACNumberView.h"
#import "ACPortSmartBtn.h"
#import "ACCircleView.h"
#import "ACTouchPortForPanView.h"
#import "YLZHoledView.h"
#import "ACCustomAlertView.h"
#import "ACUserLoginManage.h"
#import "ACTestView.h"
#define MACCOUNT 12
@interface  ACCircleView()<ACTouchPortForPanViewForCallBack,YLZHoledViewDelegate>{
    CGFloat _smartRadius;  // 内层园的半径，默认是转盘的大小
    CGFloat _bigRadius;  // 外层园的半径
    CGPoint _centerPoint; // 中心点
    CGFloat _deltaAngle; // 角度
    CGFloat currentAngle ;
    CGFloat imgViewW ;  // 外部端口的宽度
    CGFloat imgViewH ;  // 外部端口的高度
    CGFloat centerX ;   // 转盘的中心点
    CGFloat centerY ;
    ACPortBtnBase * currentTouchBtn;// 当前触摸的按钮
    
}
@property(nonatomic,weak) UIImageView * circleCenterView;   // 转盘
@property(nonatomic,weak) UIImageView * rotateRightView;   // 转盘右边
@property (nonatomic,strong) NSMutableArray * smartPortArr; // 内部水桶集合
@property (nonatomic,strong) NSMutableArray * bigPortArr; // 外部水桶集合
@property(nonatomic,weak) ACTouchPortForPanView * currentPan;// 当前的弹出面板
@property(nonatomic,weak) UIView * panBGView;// 当前的弹出面板暗黑背景
@property(nonatomic,weak) UIImageView * smartViewWithPan;// 面板的小圆角
@property (nonatomic, weak) YLZHoledView *holedView; //遮罩层
@property(nonatomic,weak) UILabel * cClabel;
@property(nonatomic,weak) UILabel * cCountLabel; // 冲程计算

@end


#define MAXPORTCOUNT 12
@implementation ACCircleView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setUpChildView];

    }
    return self;
}

#pragma mark 设置背景
- (void)setUpChildView {
  
    // 用于配置端口数
    centerX = self.frame.size.width * 0.5;
    centerY = self.frame.size.height * 0.6 + 20;
    // 转盘中心
    UIImageView * circleCenterView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Round"]];
    circleCenterView.layer.position = CGPointMake(centerX, centerY);
    circleCenterView.tag = 2;
    _circleCenterView = circleCenterView;
    [self addSubview:circleCenterView];
    // 转盘的右边
    UIImageView * rotateRightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg-black"]];
    rotateRightView.tag = 3;
    [self addSubview:rotateRightView];
    _rotateRightView = rotateRightView;
    [self bringSubviewToFront:_circleCenterView];

    [self initUI];
    
    _deltaAngle = M_PI / 6.0f;
     currentAngle = 0;
     imgViewW = 34;
     imgViewH = 34 ;
    self.smartPortArr = [NSMutableArray array];
    self.bigPortArr = [NSMutableArray array];
    for (int i = 0; i < MAXPORTCOUNT; i++) {
        // 内部的
        ACPortSmartBtn * smartImgView = [[ACPortSmartBtn alloc] initWithFrame:CGRectMake(0, 0, imgViewW, imgViewH)];
        smartImgView.tag = i;  // 设定tag值，为了后续决定弹出面板的位置
         smartImgView.colorTag = PORTKNOWNCOLOR;
        [smartImgView setBackgroundImage:[UIImage imageNamed:@"portClose"] forState:UIControlStateNormal];
        [self addSubview:smartImgView];
        [self.smartPortArr addObject:smartImgView];
        [smartImgView addTarget:self action:@selector(touchAndSetUpPort:) forControlEvents:UIControlEventTouchUpInside];
        
        // 外部的
        ACNumberView *bigImageView = [[ACNumberView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        bigImageView.tag = i;
        bigImageView.colorTag = PORTKNOWNCOLOR;
        [bigImageView setBackgroundImage:[UIImage imageNamed:@"Round-gray"] forState:UIControlStateNormal];
        bigImageView.transform = CGAffineTransformMakeRotation(currentAngle);
        [self addSubview:bigImageView];
        [self.bigPortArr addObject:bigImageView];
        [bigImageView addTarget:self action:@selector(touchAndSetUpPort:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self configConstraints];

}

- (void) initUI{
    // cc
    CGFloat ccLableX = SCREEN_WIDTH * 0.5 + 20;
    CGFloat ccLableY = 0.0;
    if(SCREEN_HEIGHT == 568){
        ccLableY = CGRectGetMinY(self.circleCenterView.frame) + 70;
    }else if (SCREEN_HEIGHT == 667) {
        ccLableY = CGRectGetMinY(self.circleCenterView.frame) + 65;
    }else if (SCREEN_HEIGHT == 736){
         ccLableY = CGRectGetMinY(self.circleCenterView.frame) + 60;
    }
    CGFloat ccLabelW = 15;
    CGFloat ccLabelH = 15;
    UILabel * ccLabel = [[UILabel alloc] initWithFrame:CGRectMake(ccLableX, ccLableY, ccLabelW, ccLabelH)];
    ccLabel.text = @"cc";
    ccLabel.font = [UIFont systemFontOfSize:12];
    ccLabel.textColor = [UIColor whiteColor];
    [self addSubview:ccLabel];
    self.cClabel = ccLabel;
    
    // 冲程数
    CGFloat countLabelY = CGRectGetMaxY(ccLabel.frame);
    CGFloat countLabelW = 70;
    CGFloat countLabelH = 20;
    CGFloat countLableX = SCREEN_WIDTH * 0.5 - countLabelW * 0.5;
    UILabel * ccCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(countLableX, countLabelY, countLabelW, countLabelH)];
    ccCountLabel.text = @"000.00";
    ccCountLabel.font = [UIFont systemFontOfSize:16];
    ccCountLabel.textColor = [UIColor whiteColor];
    ccCountLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:ccCountLabel];
    self.cCountLabel = ccCountLabel;

}


- (void)setCurrLayer:(NSInteger)currLayer{
    
    [self removeSubviewWithPanView];
 
    CGFloat offetAngle = 0;
    // 层级之间的错位
    if (currLayer % 2 != 0) {
        offetAngle = 0.2;
    }
    for (int i = ((int)currLayer * MACCOUNT); i < MACCOUNT * ((int) currLayer + 1); i++) {
        currentAngle = _deltaAngle * i + offetAngle;
        // 内部的
        CGFloat  smartImageViewX = centerX + _smartRadius * sin(currentAngle);
        CGFloat smartImageViewY = centerY - _smartRadius * cos(currentAngle);
        // 外部的
        CGFloat  bigImageViewX = centerX + _bigRadius * sin(currentAngle);
        CGFloat  bigImageViewY = centerY - _bigRadius * cos(currentAngle);
        // 内部的
        ACPortSmartBtn * smartImgView = self.smartPortArr[i - currLayer * MACCOUNT];
        smartImgView.center = CGPointMake(smartImageViewX, smartImageViewY);
        smartImgView.transform = CGAffineTransformMakeRotation(currentAngle );
        // 外部的
        ACNumberView *bigImageView  = self.bigPortArr[i - currLayer * MACCOUNT];
        bigImageView.center = CGPointMake(bigImageViewX, bigImageViewY);
        bigImageView.transform = CGAffineTransformMakeRotation(currentAngle);
        NSString * portLable = @"";
        portLable = [NSString stringWithFormat:@"%d",(i + 1)];
        [bigImageView setLableWithCountNumber:self andText:portLable andAngle:currentAngle];
    }
    
    [self bringSubviewToFront:_circleCenterView];
    [self bringSubviewToFront:self.cClabel];
    [self bringSubviewToFront: self.cCountLabel ];
   
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self removeSubviewWithPanView];
}



- (void) removeSubviewWithPanView{
    if (self.currentPan) {
        [self.currentPan removeFromSuperview];
        self.currentPan = nil;
    }
    if (self.smartViewWithPan) {
        [self.smartViewWithPan removeFromSuperview];
        self.smartViewWithPan = nil;
    }
    if (self.panBGView) {
        [self.panBGView removeFromSuperview];
        self.panBGView = nil;
    }
}


#pragma mark **************** 弹出面板 ，设置端口颜色 ****************
- (void) touchAndSetUpPort:(ACPortBtnBase *)sender{
    [self removeSubviewWithPanView];
//    ACPortBtnBase * baseSender = (ACPortBtnBase*)sender;
    UIView * BG = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    BG.alpha = 0.5;
    [self addSubview:BG];
    self.panBGView = BG;
    currentTouchBtn = sender;
    
    CGPoint btnObjX = sender.origin;
    CGFloat objX = 0;
    CGFloat objY = 0;
    CGFloat smartImagePanX = 0;
    CGFloat smartImagePanY = 0;
    // 弹出面板（ps:图的原因，然后代码就一坨坨的样子了。）
    NSInteger objTag = sender.tag ;
    ACTouchPortForPanView * panView = [[ACTouchPortForPanView alloc] init];
    panView.panViewDelegate = self;
   
    // 小圆角
    UIImageView * smartImage = [[UIImageView alloc] init];
    if(objTag >= 0 && objTag < 6){
        // 在右边
        smartImage.image = [UIImage imageNamed:@"rightCol"];
        if(objTag == 0 || objTag == 1 || objTag == 2){
            // 向下
            panView.layer.anchorPoint = CGPointMake(1, 0);
            objY = btnObjX.y - 30;
            smartImagePanY = btnObjX.y + 4;
        }else{
            // 向上
            panView.layer.anchorPoint = CGPointMake(1, 1);
            objY = btnObjX.y + 40;
            // 垂直翻转
            smartImage.transform = CGAffineTransformScale(smartImage.transform, 1.0, -1.0);
            smartImagePanY = btnObjX.y - 5;
        }
        objX = btnObjX.x - 10;
        smartImagePanX = objX - 15;
    }else{
        // 在左边
        smartImage.image = [UIImage imageNamed:@"leftCor"];
        if(objTag == 10 || objTag == 11){
            // 向下
            panView.layer.anchorPoint = CGPointMake(0, 0);
            objY = btnObjX.y - 20;
            smartImagePanY = btnObjX.y - 8;
            
        }else{
            // 向上
            panView.layer.anchorPoint = CGPointMake(0, 1);
            objY = btnObjX.y + 40;
            // 垂直翻转
            smartImage.transform = CGAffineTransformScale(smartImage.transform, 1.0, -1.0);
            smartImagePanY = btnObjX.y - 5;
        }
        objX = btnObjX.x + 50;
        smartImagePanX = objX - 15;
    }
    panView.layer.position = CGPointMake(objX, objY);
    smartImage.frame = CGRectMake(smartImagePanX, smartImagePanY, 30, 30);
    [self addSubview:smartImage];
    [self addSubview:panView];
    self.currentPan = panView;
    self.smartViewWithPan = smartImage;
}



#pragma mark 增加约束  大圆、小圆的半径、转盘中心的大小
- (void) configConstraints{
   
    if(SCREEN_HEIGHT == 480){ //3.5
    }else if(SCREEN_HEIGHT == 568){ // 4.0
        self.circleCenterView.transform = CGAffineTransformMakeScale(0.65, 0.65);
        self.rotateRightView.layer.position = CGPointMake(centerX + self.circleCenterView.size.width * 0.5, centerY );
        self.rotateRightView.bounds = CGRectMake(0, 0, SCREEN_WIDTH * 0.5 - 70 , self.rotateRightView.size.height);
        _smartRadius = _circleCenterView.size.width * 0.5 + 5;
        _bigRadius = _smartRadius + 26;
        
    }else if(SCREEN_HEIGHT == 667){ // 4.7
        self.circleCenterView.transform = CGAffineTransformMakeScale(0.7, 0.7);
        self.rotateRightView.layer.position = CGPointMake(centerX + self.circleCenterView.size.width * 0.5, centerY );
        self.rotateRightView.bounds = CGRectMake(0, 0, SCREEN_WIDTH * 0.5 - 70 , self.rotateRightView.size.height);
         _smartRadius = _circleCenterView.size.width * 0.5 + 5;
        _bigRadius = _smartRadius + 35;
    }else if (SCREEN_HEIGHT == 736){ //5.5
        self.circleCenterView.transform = CGAffineTransformMakeScale(0.8, 0.8);
        self.rotateRightView.layer.position = CGPointMake(centerX + self.circleCenterView.size.width * 0.5, centerY );
        self.rotateRightView.bounds = CGRectMake(0, 0, SCREEN_WIDTH * 0.5 - 70 , self.rotateRightView.size.height);
        _smartRadius = _circleCenterView.size.width * 0.5 + 5;
        _bigRadius = _smartRadius + 40;
    }
   
}

#pragma  mark  获取到数组中指定元素的下标
- (int) getIndexForObjWithArray:(id)obj andArray:(NSArray *)arr{
    for(int index = 0; index < arr.count; index++){
        if (arr[index] == obj) {
                return index;
            }
        }
    return -1;
}


/*
 加载配置表里面的信息，网络请求获取到数据后
 1、显示第一层的额内容
 2、给端口的colorTag给上值.注意，只是设置了当前层了的colorTag，其余层的，在setUpChildView的时候，从plist文件中设置进去
 */
- (void)configCurrentInformationWithPos:(NSInteger)pos andColorTag:(NSInteger)colorTag andCurrLayer:(NSInteger)currLayer andIndexLayer:(NSInteger)indexLayer{
    
    ACPortBtnBase * smartView = (ACPortBtnBase *)self.smartPortArr[pos];
     ACPortBtnBase * bigView = (ACPortBtnBase *)self.bigPortArr[pos];
    [smartView setBackgroundImage:[UIImage imageNamed:[self getSmartViewWithImageName:(PORTCOLOR)colorTag]] forState:UIControlStateNormal] ;
    [bigView setBackgroundImage:[UIImage imageNamed:[self getBigViewWithImageName:(PORTCOLOR)colorTag]] forState:UIControlStateNormal] ;
    bigView.colorTag = (PORTCOLOR)colorTag;
    smartView.colorTag = (PORTCOLOR)colorTag;
}



#pragma makr  ******** ACTouchPortForPanView 的delegate 方法   tagIndex 回传当前触摸的颜色标记********
- (void)touchPanViewCallBackWithIndex:(NSInteger)tagIndex{
    [UD setObject:@(1) forKey:@"isEditDviceConfig"];
    [self removeSubviewWithPanView];
    UIButton * tempBtn = nil;
    NSInteger currIndex = currentTouchBtn.tag; // 当前层的下标位置
    // 设置颜色
    if ([self.circleViewDelegate respondsToSelector:@selector(portCallBackIndex:andLayer:andTag:andOldColorTag:)]) {
        [self.circleViewDelegate portCallBackIndex:currIndex andLayer:self.currLayer andTag:tagIndex andOldColorTag:currentTouchBtn.colorTag];
    }
    if ([self.smartPortArr containsObject:currentTouchBtn]) {
        // 触摸的按钮是内部的。设置外部
        tempBtn = self.bigPortArr[currIndex];
        [currentTouchBtn setBackgroundImage:[UIImage imageNamed:[self getSmartViewWithImageName:(PORTCOLOR)tagIndex]] forState:UIControlStateNormal];
        [tempBtn setBackgroundImage:[UIImage imageNamed:[self getBigViewWithImageName:(PORTCOLOR)tagIndex]] forState:UIControlStateNormal];
    }else{
        // 触摸的按钮是外部的。设置内部
        tempBtn = self.smartPortArr[currIndex];
        [currentTouchBtn setBackgroundImage:[UIImage imageNamed:[self getBigViewWithImageName:(PORTCOLOR)tagIndex]] forState:UIControlStateNormal];
        [tempBtn setBackgroundImage:[UIImage imageNamed:[self getSmartViewWithImageName:(PORTCOLOR)tagIndex]] forState:UIControlStateNormal];
    }
     // 替换原来的下标值
    [self updateBtnColorTag:tagIndex withPos:currIndex];
}



#pragma mark 计算冲程
- (void) calcalatePortOutPut:(NSInteger) colorTag{
    
    NSString * portPath = [[NSBundle mainBundle] pathForResource:@"ACPortCC.plist" ofType:nil];
    NSDictionary * portDic = [NSDictionary dictionaryWithContentsOfFile:portPath];
    if (colorTag == -1) {
        // 第一次获取到数据计算
        NSDictionary * tempPortCount = [UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName]];
      
        CGFloat totalPort = 0.0;
        for (NSString * keyValue in tempPortCount.allKeys) {
             CGFloat portOut =  [[portDic objectForKey:keyValue] floatValue];// 每种颜色对应的冲程
            totalPort += [[tempPortCount objectForKey:keyValue] floatValue] * portOut;
        }
         self.cCountLabel.text = [NSString stringWithFormat:@"%.3f",totalPort];
    }
}



#pragma mark 更新btn的colorTag。
- (void) updateBtnColorTag:(NSInteger)colorTag withPos:(NSInteger)pos{

    ACPortBtnBase * smartView = (ACPortBtnBase *)self.smartPortArr[pos];
    ACPortBtnBase * bigView = (ACPortBtnBase *)self.bigPortArr[pos];
    bigView.colorTag = (PORTCOLOR)colorTag;
    smartView.colorTag = (PORTCOLOR)colorTag;
    if (currentTouchBtn) {
        currentTouchBtn = nil;
    }
}

- (NSString *)getSmartViewWithImageName:(PORTCOLOR) TAG{
    if(TAG == PORTREDCOLOR){return @"rotate-red";}
    else if (TAG == PORTGREENCOLOR){return @"green";}
    else if (TAG == PORTYELLOWCOLOR){return @"yellow";}
    else if (TAG == PORTBLUECOLOR){return @"portBtnblue";}
    else if (TAG == PORTGRAYCOLOR){return @"gray";}
    else if (TAG == PORTBLACKCOLOR){return @"blacka";}
    else
        return @"portClose";
}

- (NSString *)getBigViewWithImageName:(PORTCOLOR) TAG{
    if(TAG == PORTREDCOLOR){return @"Round-red";}
    else if (TAG == PORTGREENCOLOR){return @"Round-green";}
    else if (TAG == PORTYELLOWCOLOR){return @"Round-yellow";}
    else if (TAG == PORTBLUECOLOR){return @"Round-blue";}
    else if (TAG == PORTGRAYCOLOR){return @"Round-lightgrey";}
    else if (TAG == PORTBLACKCOLOR){return @"Round-black";}
    else
        return @"Round-gray";
}


- (void)openSelectPortMaskLayerForGuid4{
  
    if ([[UD objectForKey:@"maskLayerGuid4"] intValue]) {
        // 添加引导
        [self addNewUserGuidMaskLayer:CGRectMake(SCREEN_WIDTH * 0.5 - 50,SCREEN_HEIGHT* 0.4 - 60,100,100) layerRadius:50 fingerRect:CGPointMake(SCREEN_WIDTH * 0.5 + 10,SCREEN_HEIGHT * 0.5 - 20) holdViewTag:0];
    }
}


// 添加-------端口按钮的引导-----设置对应的冲程的引导----- 设置推荐配置引导
/**
 *   加入引导界面
 *
 *  @param showRect   需要引导的区域
 *  @param radius     引导的区域是否是圆形，如果是传入小于等于0的值就是矩形，反之就是圆形
 *  @param fingerRect 手指引导的区域
 *  @param hTag       回调到标示，根据holedView的tag来对应回调
 holedView:(YLZHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index
 */
- (void) addNewUserGuidMaskLayer:(CGRect) showRect layerRadius:(NSInteger)radius fingerRect:(CGPoint) fingerRect holdViewTag:(NSInteger) hTag{
    //添加遮罩指示
    
    YLZHoledView * tempMaskView = [[YLZHoledView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    tempMaskView.holeViewDelegate = self;
    if (hTag == 0) {
        UIImageView * guidLableView_1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Guidchongchen"]];
        [guidLableView_1 sizeToFit];
        guidLableView_1.center = CGPointMake(showRect.origin.x + 50, showRect.origin.y - 30);
        [tempMaskView addSubview:guidLableView_1];
        
        UIImageView * guidLableView_2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Guidchongchenshuoming@3x.png"]];
        [guidLableView_2 sizeToFit];
        guidLableView_2.center = CGPointMake(showRect.origin.x + 50, showRect.origin.y + 150);
        guidLableView_2.transform = CGAffineTransformMakeScale(1.1, 1.1);
        [tempMaskView addSubview:guidLableView_2];
    }
    [tempMaskView initWithMaskLayerWithObj:showRect layerRadius:radius fingerRect:fingerRect holdViewTag:hTag];
    [[UIApplication sharedApplication].keyWindow addSubview:tempMaskView];
    self.holedView = tempMaskView;
}


- (void)holedView:(YLZHoledView *)holedView didSelectHoleAtIndex:(NSUInteger)index{
    if (index == 0) {
        if (self.holedView.tag == 0) {
           [self.holedView removeFromSuperview];
            [UD setObject:@(0) forKey:@"maskLayerGuid4"];
            [UD setObject:@(1) forKey:@"maskLayerGuid5"];
            ACPortSmartBtn * smartPorttBtn = (ACPortSmartBtn *)self.smartPortArr[0];
            // 引导4 ---------- 弹出面板
            [self touchAndSetUpPort:smartPorttBtn];
            // 弹出面板的遮罩
            [self addNewUserGuidMaskLayer:CGRectMake(self.currentPan.origin.x,self.currentPan.origin.y + 60, self.currentPan.size.width, 40) layerRadius:-1 fingerRect:CGPointMake(self.currentPan.center.x, self.currentPan.center.y + 100)  holdViewTag:1];
           
            
        }else if (self.holedView.tag == 1){
            [UD setObject:@(0) forKey:@"maskLayerGuid5"];
            [UD setObject:@(1) forKey:@"maskLayerGuid6"];
            [self.holedView removeFromSuperview];
            // 引导5 --------- 选定红色的端口，并发送消息，通知开启引导6
            [self touchPanViewCallBackWithIndex:0];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"openSaveMaskLayer" object:nil userInfo:nil];
           
        }
    }
}



@end
